<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h2>管理员数据仪表盘</h2>
      <el-button type="primary" @click="refreshData" :loading="loading">刷新数据</el-button>
    </div>

    <!-- 数据摘要卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>文章总数</span>
            <el-icon><Document /></el-icon>
          </div>
        </template>
        <div class="stat-value">{{ dashboardData.totalArticles || 0 }}</div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>用户总数</span>
            <el-icon><User /></el-icon>
          </div>
        </template>
        <div class="stat-value">{{ dashboardData.totalUsers || 0 }}</div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>分类总数</span>
            <el-icon><Folder /></el-icon>
          </div>
        </template>
        <div class="stat-value">{{ dashboardData.totalCategories || 0 }}</div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>评论总数</span>
            <el-icon><ChatLineRound /></el-icon>
          </div>
        </template>
        <div class="stat-value">{{ dashboardData.totalComments || 0 }}</div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="chart-row">
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>文章状态分布</span>
          </div>
        </template>
        <div id="article-status-chart" class="chart"></div>
      </el-card>

      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>分类文章统计</span>
          </div>
        </template>
        <div id="category-stat-chart" class="chart"></div>
      </el-card>
    </div>

    <div class="chart-row">
      <el-card class="chart-card full-width" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>阅读量最高的文章</span>
          </div>
        </template>
        <div id="top-articles-chart" class="chart"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Document, User, Folder, ChatLineRound } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import * as echarts from 'echarts'

const dashboardData = ref({
  totalArticles: 0,
  pendingArticles: 0,
  publishedArticles: 0,
  rejectedArticles: 0,
  totalUsers: 0,
  totalCategories: 0,
  totalComments: 0,
  topArticles: [],
  categoryStats: []
})

const loading = ref(false)
let charts = []

// 初始化时加载数据
onMounted(() => {
  fetchDashboardData()
})

// 组件卸载时销毁图表实例
onUnmounted(() => {
  charts.forEach(chart => {
    if (chart) {
      chart.dispose()
    }
  })
})

// 获取仪表盘数据
const fetchDashboardData = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    console.log('发送仪表盘数据请求');
    const response = await axios.get('/api/articles/dashboard', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    console.log('仪表盘数据响应:', response);
    dashboardData.value = response.data
    renderCharts()
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    ElMessage.error('获取仪表盘数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchDashboardData()
}

// 渲染所有图表
const renderCharts = () => {
  // 清除之前的图表实例
  charts.forEach(chart => {
    if (chart) {
      chart.dispose()
    }
  })
  charts = []

  // 延迟一些时间确保DOM已经更新
  setTimeout(() => {
    renderArticleStatusChart()
    renderCategoryStatChart()
    renderTopArticlesChart()
  }, 100)
}

// 文章状态分布饼图
const renderArticleStatusChart = () => {
  const chartDom = document.getElementById('article-status-chart')
  const chart = echarts.init(chartDom)
  charts.push(chart)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: ['待审核', '已发布', '被拒绝']
    },
    series: [
      {
        name: '文章状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: dashboardData.value.pendingArticles, name: '待审核' },
          { value: dashboardData.value.publishedArticles, name: '已发布' },
          { value: dashboardData.value.rejectedArticles, name: '被拒绝' }
        ]
      }
    ]
  }
  
  chart.setOption(option)
  
  // 监听窗口大小变化，自适应调整图表大小
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 分类文章统计柱状图
const renderCategoryStatChart = () => {
  if (!dashboardData.value.categoryStats || dashboardData.value.categoryStats.length === 0) {
    return
  }
  
  const chartDom = document.getElementById('category-stat-chart')
  const chart = echarts.init(chartDom)
  charts.push(chart)
  
  const categories = dashboardData.value.categoryStats.map(item => item.categoryName)
  const counts = dashboardData.value.categoryStats.map(item => item.articleCount)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '文章数量',
        type: 'bar',
        data: counts,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 阅读量最高的文章条形图
const renderTopArticlesChart = () => {
  if (!dashboardData.value.topArticles || dashboardData.value.topArticles.length === 0) {
    return
  }
  
  const chartDom = document.getElementById('top-articles-chart')
  const chart = echarts.init(chartDom)
  charts.push(chart)
  
  // 截取文章标题，避免过长
  const titles = dashboardData.value.topArticles.map(item => {
    return item.title.length > 20 ? item.title.substring(0, 20) + '...' : item.title
  })
  const viewCounts = dashboardData.value.topArticles.map(item => item.viewCount)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '浏览量'
    },
    yAxis: {
      type: 'category',
      data: titles,
      axisLabel: {
        interval: 0
      }
    },
    series: [
      {
        name: '浏览量',
        type: 'bar',
        data: viewCounts,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#ffb980' },
            { offset: 0.5, color: '#ff7b3a' },
            { offset: 1, color: '#ff7b3a' }
          ])
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}
</script>

<style scoped>
.dashboard-container {
  padding: 0 20px 20px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #606266;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
  padding: 10px 0;
}

.chart-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart {
  height: 330px;
}

.full-width {
  grid-column: span 2;
}

@media (max-width: 1200px) {
  .stat-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .chart-row {
    grid-template-columns: 1fr;
  }
  
  .full-width {
    grid-column: span 1;
  }
}

@media (max-width: 768px) {
  .stat-cards {
    grid-template-columns: 1fr;
  }
}
</style> 